package com.spark.gaea.data.mybatis;

import com.spark.gaea.data.ICounterDao;
import com.spark.gaea.data.mybatis.vo.Counter;
import com.spark.gaea.data.vo.ICounter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class CounterDao implements ICounterDao {
	public static final String CLASS_NAME;
	private static final String DEFAULT_NAME = "DEFAULT";
	private static final int START_ID = 1;
	@Autowired
	private Dao dao;

	@Override
	public List<ICounter> listAllCounters() {
		return this.dao.getList(CounterDao.CLASS_NAME, "listAllCounters");
	}

	@Override
	public Long increment() {
		return this.increment("DEFAULT");
	}

	@Override
	public Long increment(final int step) {
		return this.increment("DEFAULT", step);
	}

	@Override
	public Long increment(final String name) {
		return this.increment(name, 1);
	}

	@Override
	public Long increment(final String name, final int step) {
		ICounter counter = this.dao.get(CounterDao.CLASS_NAME, "getCounterByName", name);
		if (counter == null) {
			counter = new Counter();
			counter.setName(name);
			counter.setCurrentId((long) step);
			this.dao.insert(CounterDao.CLASS_NAME, "insert", counter);
		} else {
			counter.setCurrentId(counter.getCurrentId() + step);
			this.dao.update(CounterDao.CLASS_NAME, "update", counter);
		}
		return counter.getCurrentId();
	}

	@Override
	public void rename(final String oldName, final String newName) {
		if (oldName != null && newName != null && !"DEFAULT".equals(oldName) && !"DEFAULT".equals(newName)) {
			ICounter counter = this.dao.get(CounterDao.CLASS_NAME, "getCounterByName", newName);
			if (counter == null) {
				counter = this.dao.get(CounterDao.CLASS_NAME, "getCounterByName", oldName);
				if (counter == null) {
					this.increment(newName);
				} else {
					counter.setName(newName);
					this.dao.update(CounterDao.CLASS_NAME, "update", counter);
				}
			}
		}
	}

	@Override
	public void reset() {
		this.reset("DEFAULT");
	}

	@Override
	public void reset(final String name) {
		this.dao.delete(CounterDao.CLASS_NAME, "delete", name);
	}

	static {
		CLASS_NAME = CounterDao.class.getName() + '.';
	}
}
